package com.ayf.payment.game.api.controller.paychannel;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.type.OrderStatus;
import com.ayf.payment.game.api.utils.RSA;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.ayf.payment.game.api.wx.WxSendMsgUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

@RequestMapping("/v/wanxyft/pay")
@RestController
public class WanXYFTPayNotifyController extends BasePayNotifyController{

    @Autowired
    private WxSendMsgUtils wxSendMsgUtils;

    @RequestMapping("/notify")
    public void notify(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter pw = null;
        String traceId = SnowFlakeUtils.getTraceId();
        try {
            String requestBody = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
            String sign = request.getHeader("sign");
            if(StringUtils.isBlank(requestBody) || StringUtils.isBlank(sign)){
                LogPortal.error("{} 易分通交易异步通知内容格式错误",traceId);
                pw.write("fail");
                pw.flush();
                return;
            }
            JSONObject plcyObject = JSONObject.parseObject(requestBody);
            JSONObject dataObject = JSONObject.parseObject(plcyObject.getString("data"));
            String orderId=dataObject.getString("merchant_order_no");
            if (StringUtils.isEmpty(orderId)){
                LogPortal.info("{} 易分通交易推送过来到商户订单号数值为空，不进行后续操作",traceId);
                pw.write("success");
                pw.flush();
                return;
            }
            super.notifyAsync(request,response,orderId);
        } catch (Exception e) {
            LogPortal.error("{} 易分通交易异步通知验签业务逻辑处理失败，具体原因:{}",e,traceId,e.getMessage());
            pw.write("异步通知响应验签处理失败："+e.getMessage());
            pw.flush();
        }finally {
            if(pw != null)
                pw.close();
        }
    }

    /**
     * 代付异步通知处理
     */
    @RequestMapping("/paynotify")
    public void payNotify(HttpServletRequest request, HttpServletResponse response) {
    }

    @RequestMapping("/returns")
    public void returns(HttpServletRequest request, HttpServletResponse response) {
       
    }

    @Override
    protected void notifyAsyncBusinesExec(HttpServletRequest request, HttpServletResponse response,Object obj) {
        PrintWriter pw = null;
        String traceId = SnowFlakeUtils.getTraceId();
        try {
            pw = response.getWriter();
            String requestBody = StreamUtils.copyToString(request.getInputStream(),StandardCharsets.UTF_8);
            LogPortal.info("{} 易分通交易异步通知 请求参数：{}",traceId,requestBody);
            String sign = request.getHeader("sign");
            JSONObject plcyObject = JSONObject.parseObject(requestBody);
            JSONObject dataObject = JSONObject.parseObject(plcyObject.getString("data"));
            String orderId=dataObject.getString("merchant_order_no");
            String channelOrderStatus = dataObject.getString("status");
            if (!"FAIL".equals(channelOrderStatus) && !"SUCCESS".equals(channelOrderStatus)){
                LogPortal.info("{} 易分通交易异步通知 订单号[{}]渠道状态[{}]，渠道状态不是成功或失败，不进行后续操作",traceId,orderId,channelOrderStatus);
                pw.write("success");
                pw.flush();
                return;
            }
            Order order= orderService.selectByMerchantOrderNo(orderId);
            if(order==null ){
                LogPortal.error("{} 易分通交易异步通知 订单号[{}]在我方系统查询不到",traceId,orderId);
                pw.write("success");
                pw.flush();
                return;
            }
            if(OrderStatus.SUCCESS.equals(order.getOrderStatus()) || OrderStatus.FAIL.equals(order.getOrderStatus())){
                LogPortal.error("{} 易分通交易异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]",traceId,orderId,order.getOrderStatus().name(),channelOrderStatus);
                pw.write("success");
                pw.flush();
                return;
            }
            boolean signCheck = RSA.verify(requestBody, sign, systemInitialization.channelDTO(order.getPayChannleId()).getChannelPublicKey());
            if (!signCheck) {
                LogPortal.error("{} 易分通交易异步通知 商户订单号[{}] 异步通知验签失败",traceId,orderId);
                pw.write("fail");
                pw.flush();
                return;
            }
            OrderStatus orderStatus = OrderStatus.PROCESSING;
            if ("FAIL".equals(channelOrderStatus)){
                orderStatus = OrderStatus.FAIL;
                order.setScriptStatus(-1);
            } else if ("SUCCESS".equals(channelOrderStatus)){
                orderStatus = OrderStatus.SUCCESS;
            }
            if (!OrderStatus.PROCESSING.equals(orderStatus)){
                order.setOrderStatus(orderStatus);
                orderService.paymentOrder(order,dataObject);
                if (OrderStatus.SUCCESS.equals(orderStatus)){
                    orderService.orderToGetWay(order);
                    try {
                        wxSendMsgUtils.rechargeSuccess(order);
                    } catch (Exception e) {
                        LogPortal.error("{} 易分通交易异步通知 商户订单号[{}]CallBack 微信通知异常", e, traceId, orderId);
                    }
                }
            }
            LogPortal.info("{} 易分通交易异步通知 商户订单号[{}]CallBack 异步通知验签成功且业务处理成功",traceId,orderId);
            pw.write("success");
            pw.flush();
        } catch (Exception e) {
            LogPortal.error("{} 易分通交易异步通知验签业务逻辑处理失败，具体原因:{}",e,traceId,e.getMessage());
            pw.write("异步通知响应验签处理失败："+e.getMessage());
            pw.flush();
        }finally {
            if(pw != null)
                pw.close();
        }
    }

    @Override
    protected void notifySyncBusinesExec(HttpServletRequest request, HttpServletResponse response) {

    }

    @Override
    protected void agentPayNotifyAsyncBusinesExec(HttpServletRequest request, HttpServletResponse response,Object obj) {
    }
}
